package com.tianxiao.faas.application.web.corner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.tianxiao.faas.api.param.corner.*;
import com.tianxiao.faas.application.aop.AuthenticationContextHolder;
import com.tianxiao.faas.biz.corner.service.user.UserService;
import com.tianxiao.faas.biz.domain.entity.ShopDetailEntity;
import com.tianxiao.faas.biz.service.corner.ShopService;
import com.tianxiao.faas.common.access.Access;
import com.tianxiao.faas.common.result.Result;
import com.tianxiao.faas.common.util.GeoUtils;
import com.tianxiao.faas.common.util.PageUtils;
import com.tianxiao.faas.common.util.StringUtils;
import com.tianxiao.faas.mapper.dao.ConcernModelMapper;
import com.tianxiao.faas.mapper.dao.FootPrintModelMapper;
import com.tianxiao.faas.mapper.dao.GoodsModelMapper;
import com.tianxiao.faas.mapper.model.*;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/app/shop")
public class ShopController {
    @Resource
    private ShopService shopService;
    @Resource
    private GoodsModelMapper goodsModelMapper;
    @Resource
    private ConcernModelMapper concernModelMapper;
    @Resource
    private FootPrintModelMapper footPrintModelMapper;

    @RequestMapping(value = "/getTags")
    public Result<List<TagEntity>> getTags(boolean all) {
        return Result.builder().data(shopService.getTags(all)).success(true);
    }

    @RequestMapping(value = "/order")
    @Access
    public Result<Boolean> order(@RequestParam("shopId") Long shopId) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        if (shopId == null) {
            return Result.builder().msg("店铺不存在").success(false);
        }
        ShopModel shop = shopService.getById(shopId);
        if (shop == null) {
            return Result.builder().msg("店铺不存在").success(false);
        }
        FootPrintModel footPrintModel = footPrintModelMapper.selectByUserIdAndShopId(userId, shopId);
        if (footPrintModel == null) {
            FootPrintModel record = new FootPrintModel();
            long applyTime = System.currentTimeMillis();
            record.setApplyTime(applyTime);
            record.setCreated(applyTime);
            record.setDeleted(0);
            record.setShopId(shopId);
            record.setUpdated(applyTime);
            record.setUserId(userId);
            record.setIsArrive(0);
            footPrintModelMapper.insertSelective(record);
        }

        return Result.builder().data(true).success(true);
    }

    @RequestMapping(value = "/get")
    @Access
    public Result<ShopInfoResult> get() {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        ShopModel shop = shopService.getByUserId(userId);
        if (shop == null) {
            return Result.builder().msg("店铺不存在").success(false);
        }
        Long shopId = shop.getId();
        ShopInfoResult shopInfoParam = shopService.getShopInfoParam(shop, null, null);
        Map<Long, List<TagsModel>> longListMap =
                shopService.getLongListMap(Lists.newArrayList(shopId));
        shopInfoParam.setTags(shopService.buildTagEntity(longListMap, shopId));
        Integer integer = concernModelMapper.countByShopId(shopId);
        shopInfoParam.setFansCount(integer);
        return Result.builder().data(shopInfoParam).success(true);
    }

    @RequestMapping(value = "/getById")
    @Access(login = false)
    public Result<ShopInfoResult> getById(@RequestBody ShopPageParam param) {
        if (param.getShopId() == null) {
            return Result.builder().data(null).success(true);
        }
        ShopModel shop = shopService.getById(param.getShopId());
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        ShopInfoResult shopInfoParam = shopService.getShopInfoParam(shop, param.getLatitude(), param.getLongitude());
        Long shopId = shop.getId();
        Map<Long, List<TagsModel>> longListMap =
                shopService.getLongListMap(Lists.newArrayList(shopId));
        shopInfoParam.setTags(shopService.buildTagEntity(longListMap, shopId));
        if (userId != null) {
            Long userId1 = shop.getUserId();
            if (userId1 != null && userId1.equals(userId)) {
                shopInfoParam.setIsFans(true);
            } else {
                List<ConcernModel> concernModels = getConcernModels(userId, shopId);
                shopInfoParam.setIsFans(!CollectionUtils.isEmpty(concernModels));
            }
        }
        Integer integer = concernModelMapper.countByShopId(shopId);
        shopInfoParam.setFansCount(integer);
        return Result.builder().data(shopInfoParam).success(true);
    }

    private List<ConcernModel> getConcernModels(Long userId, Long shopId) {
        ConcernModelExample example1 = new ConcernModelExample();
        example1.createCriteria().andUserIdEqualTo(userId).andShopIdEqualTo(shopId).andDeletedEqualTo(0);
        return concernModelMapper.selectByExample(example1);
    }



    @RequestMapping(value = "/update")
    @Access
    public Result<Boolean> update(@RequestBody ShopInfoParam param) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        ShopModel shop = shopService.getByUserId(userId);
        if (shop == null) {
            return Result.builder().msg("店铺不存在").success(false);
        }
        ShopModel updateShop = new ShopModel();
        updateShop.setId(shop.getId());
        updateShop.setAddress(param.address());
        updateShop.setGreatness(param.getLatitude());
        updateShop.setLogo(param.getLogo());
        if (!CollectionUtils.isEmpty(param.getImgs())) {
            updateShop.setImages(JSON.toJSONString(param.getImgs()));
        }

        updateShop.setLongitude(param.getLongitude());
        if (param.getName() != null) {
            updateShop.setName(param.getName());
        }
        if (param.getTime() != null) {
            updateShop.setOpenTime(param.getTime());
        }
        shopService.buildShopConfig(param, shop);
        shopService.save(updateShop);

        return Result.builder().data(true).success(true);
    }

    @RequestMapping(value = "/create")
    @Access
    public Result<Boolean> create(@RequestBody ShopInfoParam param) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        ShopModel shop = shopService.getByUserId(userId);
        if (shop == null) {
            shop = new ShopModel();
        }
        shop.setUserId(userId);
        shop.setAddress(param.address());
        shop.setGreatness(param.getLatitude());
        shop.setLogo(param.getLogo());
        if (!CollectionUtils.isEmpty(param.getImgs())) {
            shop.setImages(JSON.toJSONString(param.getImgs()));
        }
        shop.setLongitude(param.getLongitude());
        shop.setName(param.getName());
        shop.setOpenTime(param.getTime());
        shopService.buildShopConfig(param, shop);
        shopService.save(shop);
        return Result.builder().data(true).success(true);
    }



    @RequestMapping(value = "/list")
    public Result<List<ShopResult>> list(@RequestBody ShopPageParam param) {
        return shopService.page(param);
    }

    @RequestMapping(value = "/tag/create")
    @Access
    public Result<Boolean> createTag(@RequestBody TagEntity param) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        ShopModel byUserId = shopService.getByUserId(userId);
        shopService.createTag(param, byUserId);
        return Result.builder().success(true).data(true);
    }

    @RequestMapping(value = "/product/create")
    @Access
    public Result<Boolean> createGoods(@RequestBody List<ProductResult> params) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        ShopModel shop = shopService.getByUserId(userId);
        shopService.saveProducts(params, shop);
        return Result.builder().success(true).data(true);
    }

    @RequestMapping(value = "/product/list")
    @Access
    public Result<List<ProductResult>> listGoods(@RequestBody ShopPageParam param) {
        Long shopId = param.getShopId();
        ShopModel shop = shopService.getById(shopId);
        if (shop == null) {
            return Result.builder().success(false).msg("店铺不存在");
        }
        List<GoodsModel> page = goodsModelMapper.page(shopId, PageUtils.getOffset(param.getPage(), param.getPageSize()), param.getPageSize());
        Integer count = goodsModelMapper.count(shopId);
        List<ProductResult> results = shopService.buildProductResults(page);
        return Result.builder().success(true).data(results).totalCount(count).pageNo(param.getPage()).pageSize(param.getPageSize())
                .totalPage();
    }

    @RequestMapping(value = "/product/getById")
    @Access
    public Result<ProductResult> listGoods(Long id) {
        GoodsModel page = goodsModelMapper.selectByPrimaryKey(id);
        if (page == null) {
            return Result.builder().success(false).msg("商品不存在");
        }

        List<ProductResult> results = shopService.buildProductResults(Lists.newArrayList(page));
        if (CollectionUtils.isEmpty(results)) {
            return Result.builder().success(false).msg("商品不存在");
        }
        ShopModel byId = shopService.getById(page.getShopId());
        ProductResult data = results.get(0);
        data.setShopName(byId.getName());
        List<String> strings = JSONArray.parseArray(byId.getImages(), String.class);
        data.setShopImgs(strings);
        return Result.builder().success(true).data(data);
    }

}
